/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.timed;

import entity.Construct;
import entity.Production;
import java.util.Collection;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import session.manager.ConstructManagerBeanLocal;
import session.manager.MessageManagerBeanLocal;
import session.manager.PlayerManagerBeanLocal;
import session.manager.ResourceManagerBeanLocal;
import util.Wrapper;

/**
 *
 * @author antonio
 */
@Stateless
public class ProductionTimedBean implements ProductionTimedBeanLocal {

    @Resource
    private TimerService timerService;
    
    @EJB
    private PlayerManagerBeanLocal playerManager;
    
    @EJB
    private ResourceManagerBeanLocal resourceManager; 
    
    @EJB
    private ConstructManagerBeanLocal constructManager;
    
    @EJB
    private MessageManagerBeanLocal messageManager;

    @Override
    public void initTimer(String username, String constructName, int amount){
        Wrapper wrapper = new Wrapper(username, constructName, amount);
        TimerConfig timerConfig = new TimerConfig(wrapper, true);
        Construct construct = constructManager.findConstruct(constructName);
        Timer timer = timerService.createSingleActionTimer(construct.getProductionTime() * 1000, timerConfig);
        System.out.print("TimedBean: start");
    }
    
    @Timeout
    public void timeout(Timer timer) {
        Wrapper wrapper = (Wrapper) timer.getInfo();
        constructManager.releaseConstructs(wrapper.getString1(), wrapper.getString2(), wrapper.getAmount());
        Construct construct = constructManager.findConstruct(wrapper.getString2());
        int amount = wrapper.getAmount();
        Collection<Production> productions = construct.getProductionCollection();
        for (Production production : productions) {
            resourceManager.increse(wrapper.getString1(), production.getResource1().getName(), production.getAmount() * amount);
        }
        messageManager.createMessage(wrapper.getString1(), "Fine Produzione " + wrapper.getString2());
        System.out.print("TimedBean: end");
    }

}
